<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SouthAfrica
 *
 * @author dragon.hu add @2016.5.11
 */
require_once 'BaseChannel.php';

//南非SDK  PayGate
class SouthAfrica implements BaseChannel 
{	
	//南非的谷歌key
	static $googlekey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4WkOvT5I1Fc7ZaAw2bISRY7l8+cOpTJ+pqM4DVIIxSHcygxifoXvUjzHMOyvzWOVgU8vhv7K17DPETpPXFk4f9YKRunUbF0NBbo+VlOpwD+k09huKv5ew+6W6IHluN5s8XbjFpr4CfDDUStX+86dE1pFuR8IfPBRVdrceEAz+3nS09TzQuEQ7nr5UCHHhA22Riw4edYzHPK4826r+oU5E4UI4oPAdDRop/PLp0w/hXxLymZqQXYMN248Ao1J6zLVFN3ltDfsH3PTtE2WU0ptLmmaDHDlrR2eFMpJlvfkNc9dUOCCHAZB507RTOjnCtheCaootVKl5Rbd0nCdsTUCXwIDAQAB";
	function __construct() 
	{
		//echo "construct";
	}

	//put your code here
	function android($data) 
	{
		return;
	}

	function ios($data) 
	{
		return;
	}
	
	//http://192.168.18.20/master/mcGM/payment/SouthAfrica/sendPayInfo?roleid=7535&serverid=20&accountid=1928&orderid=123456
	function sendPayInfo()
	{
		
		$orderLog = new ChargeOrder();
		$orderLog->log("southafrica", $_REQUEST);
		
		require (CONFIGPATH . 'db.php');
		$paydbconn = new Database($config['db']);
		
		//1.从客户端发来的数据
		$roleid = $_REQUEST['roleid'];  //角色id
		$serverid = $_REQUEST['serverid'];  //分区id
		$orderid = $_REQUEST['orderid'];  //订单id
		$productid = $_REQUEST['product_id'];  //产品id
		$accountid = $_REQUEST['accountid'];  //账号id
		//1a.客户端输入框中的数据
		$firstName = $_REQUEST['firstname'];  //名
		$lastName = $_REQUEST['lastname'];  //姓
		$Email = $_REQUEST['email'];  //Email
		$cardNumber = $_REQUEST['cardnumber'];  //信用卡号
		$cardExpiryDate = $_REQUEST['cardexpirydate'];  //mmyyyy信用卡截止时间
		$CVV = $_REQUEST['cvv'];  //CVV
		$currency = $_REQUEST['currency'];  //货币类型
		$Amount = $_REQUEST['amount'];  //数量
		
		$soapClient = new SoapClient('https://secure.paygate.co.za/PayHost/process.trans?wsdl', 
				array('trace' => 1)); //point to WSDL and set trace value to debug
		
		//print_r($soapClient->__getFunctions());
		//print_r($soapClient->__getTypes());
		//exit();
		$PayGateId = "10011064270";
		$Password = "test";
		
		//$cardNumber = "5200000000000015";
		//$cardExpiryDate = "112030";
		//$firstName = "Firstname";
		//$lastName = "Lastname";
		//$Email = "first.last@name.com";
		//$CVV = "123";
		//$currency = "ZAR";
		//$Amount = "1000";
		
		$request = <<<XML
		<SingleVaultRequest xmlns="http://www.paygate.co.za/PayHOST"> 
		<CardVaultRequest> 
		<Account> 
		<PayGateId>{$PayGateId}</PayGateId> 
		<Password>{$Password}</Password> 
		</Account>
		<CardNumber>{$cardNumber}</CardNumber> 
		<CardExpiryDate>{$cardExpiryDate}</CardExpiryDate> 
		</CardVaultRequest> 
		</SingleVaultRequest>
XML;
		$result = $soapClient->__soapCall('SingleVault', array(
				new SoapVar($request, XSD_ANYXML)
		));
		$arrResult = self::object_to_array($result);
		$orderLog->log("southafrica", $arrResult);
		//var_dump($result);
		//var_dump($result->CardVaultResponse->Status->VaultId);
		//exit();
		
		$thirdRequest = <<<XML
		<SinglePaymentRequest xmlns="http://www.paygate.co.za/PayHOST">
		<CardPaymentRequest>
		<Account>
		<PayGateId>{$PayGateId}</PayGateId>
		<Password>{$Password}</Password>
		</Account>
		<Customer>
		<FirstName>{$firstName}</FirstName>
		<LastName>{$lastName}</LastName>
		<Email>{$Email}</Email>
		</Customer>
		<VaultId>{$result->CardVaultResponse->Status->VaultId}</VaultId>
		<CVV>{$CVV}</CVV>
		<BudgetPeriod>0</BudgetPeriod>
		<Order>
		<MerchantOrderId>{$orderid}</MerchantOrderId>
		<Currency>{$currency}</Currency>
		<Amount>{$Amount}</Amount>
		</Order>
		</CardPaymentRequest>
		</SinglePaymentRequest>
XML;
		$thirdResult = $soapClient->__soapCall('SinglePayment', array(
				new SoapVar($thirdRequest, XSD_ANYXML)
		));
		//var_dump($thirdResult);
		//var_export($thirdResult);
		//exit();
		$arrThirdResult = self::object_to_array($thirdResult);
		$orderLog->log("southafrica", $arrThirdResult);
		
		//2.充值的过程
		$ResultCode = $thirdResult->CardPaymentResponse->Status->ResultCode;
		
		if ($ResultCode == '990017')
		{
			$money = $thirdResult->CardPaymentResponse->Status->Amount;  //注意要进行汇率转换！！！！！！！！！！！！
			//var_dump($money);
			$one = $paydbconn->one("SELECT exchangerate FROM southafrica_parities WHERE currencycode = '$currency'");
			$money = round($money / $one['exchangerate'], 2);  //转成了美元，保留两位有效数字
			//var_dump($one);
			//var_dump($money);
			//exit();
			
			//进行发货
			if(false == $orderLog->recordOrder(STATUS_SUCCESS, $money, $orderid, "southafrica", ANDROID))
			{
				$ret="failure";
				$orderLog->log("southafrica",array("order"=>$orderid,"money"=>$money,"serverresult"=>"faild"));
			}else
			{
				//支付成功
				$ret="success";
				$orderLog->log("southafrica",array("order"=>$orderid,"money"=>$money,"serverresult"=>"success"));
			}
		}
		else
		{
			$orderLog->log("southafrica","  order:$orderid  pay error $ResultCode");
			$ret="failure";
		}
		echo $ret;
	}
	
	static function object_to_array($obj)
	{
		$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
		foreach ($_arr as $key => $val)
		{
			$val = (is_array($val) || is_object($val)) ? self::object_to_array($val) : $val;
			$arr[$key] = $val;
		}
		return $arr;
	}
	
	function insertOrder($paydb, $orderlog, $money, $orderid, $serverid, $roleid, $accountid, $channelid, $platform, $thirdorderid = '') 
	{
		$nowtime = date ( 'Y-m-d H:i:s', time () );
		$sql = "INSERT INTO {pre}payment(orderid,serverid,roleid,accountid,create_time,status,channel,platform,appid,money,finish_time,product_id) VALUES
		('$orderid','$serverid','$roleid','$accountid','$nowtime','4','$channelid','$platform','0','$money','$nowtime','3')";
		$res = $paydb->execute ( $sql );
		if ($res == false) {
			$orderlog->log ( "error", "execute sql failed! " . $sql );
			return false;
		}
		
		$serverInfo = $paydb->one ( "SELECT * FROM {pre}areasample WHERE `id`='" . $serverid . "'" );
		$one ['orderid'] = ( string ) $orderid;
		$one ['roleid'] = ( int ) $roleid;
		$one ['channel'] = ( string ) $channelid;
		$one ['money'] = ( string ) $money;
		$one ['platform'] = ( int ) $platform;
		$one ['finish_time'] = ( string ) $nowtime;
		$one ['product_id'] = ( int ) 3;
		
		// 第几次充值
		$paytimes = 0;
		$sql = "SELECT * FROM {pre}payment WHERE serverid = " . $serverid . " AND roleid='" . $roleid . "'";
		$paydb->query ( $sql );
		$rolepayarr = array ();
		while ( $n = $paydb->get_array () ) {
			$rolepayarr [] = $n;
		}
		for($i = 0; $i < count ( $rolepayarr ); $i ++) {
			if (isset ( $rolepayarr [$i] ['money'] )) {
				$paytimes += 1;
			}
		}
		
		$one ['paytimes'] = $paytimes; // 累计支付次数
		$datas [] = $one;
		$json_str = json_encode ( $datas );
		$json_str = str_replace ( " ", "%20", $json_str );
		
		$strResult = vpost ( $serverInfo ['host'] . "json_str=$json_str&action=45", 10 ); // 请求游戏服务器发放充值
		                                                                              // 推送游戏服务器超时或者失败
		if ($strResult === FALSE || $strResult == "fail") {
			// echo "error:area sending fail ";
			// 写log
			$tmpstr = http_build_query ( $one );
			$orderlog->log ( "error", "post error!!!" . $tmpstr );
			return false;
		}
		return true;
	}

	function processPay()
	{
		$orderLog = new ChargeOrder();
		$orderLog->log("southafrica", $_REQUEST);
		//1.从客户端发来的数据
		$roleid = $_REQUEST['roleid'];
		$serverid = $_REQUEST['serverid'];
		$orderid = $_REQUEST['orderid'];
		$accountid = $_REQUEST['accountid'];
	
		$money = $_REQUEST['money'];
		//2.是否要进行一步验证
	
		//3.充值的过程
		if(1)  //验证通过
		{
			//进行发货
			if(false == $orderLog->recordOrder(STATUS_SUCCESS, $money, $orderid, "southafrica", ANDROID))
			{
				$ret="failure";
				$orderLog->log("southafrica",array("order"=>$orderid,"money"=>$money,"serverresult"=>"faild"));
			}else
			{
				//支付成功
				$ret="success";
				$orderLog->log("southafrica",array("order"=>$orderid,"money"=>$money,"serverresult"=>"success"));
			}
	
		} else {
			//"$sig验证失败"
			$orderLog->log("southafrica","  order:$orderid  sign error");
			$ret="failure";
		}
		echo $ret;
	
	}
	
	/************************************南非的谷歌支付***********************************/
	//http://52.51.52.173/master/mcGM/payment/SouthAfrica/payverify
	function payverify()
	{
		$publickey = "";  //谷歌支付的publickey
		$orderLog = new ChargeOrder();
		//var_dump($_REQUEST);
		//exit();
		//$orderLog->log("googleafrica", $_REQUEST);
		//1.接收客户端传来的数据
	
		$request = file_get_contents("php://input");
		$orderLog->log("googleafrica", $request);
		//var_dump($request);
		$tmpallarr = array();
		$tmparr = explode('&', $request);
		foreach ($tmparr as $k=>$v)
		{
			$tmp = explode('=', $v);
			$tmpallarr[$tmp[0]] = $tmp[1];
		}
		$purchaseData = $tmpallarr['purchaseData'];
		$dataSignature = $tmpallarr['dataSignature'];
		$roleid = $tmpallarr['roleid'];
		$serverid = $tmpallarr['serverid'];
		$orderid = $tmpallarr['orderid'];
		$money = $tmpallarr['money'];
		
		/*$purchaseData = stripslashes($_REQUEST['purchaseData']);
		$dataSignature = stripslashes($_REQUEST['dataSignature']);
		$roleid = $_REQUEST['roleid'];
		$serverid = $_REQUEST['serverid'];
		$orderid = $_REQUEST['orderid'];
		$money = $_REQUEST['money'];*/
		//2.sign验证
		//var_dump(self::$googlekey);
		//var_dump($purchaseData);
		//var_dump($dataSignature);
		$return = $this->chkGooglePlay(self::$googlekey, $purchaseData, $dataSignature);
		//var_dump($return);
		//exit();
		if ($return)
		{
			//进行发货
			if(false == $orderLog->recordOrder(STATUS_SUCCESS, $money, $orderid, "googleafrica", ANDROID))
			{
				$ret="failure";
				$orderLog->log("googleafrica",array("order"=>$orderid,"money"=>$money,"serverresult"=>"faild"));
			}
			else
			{
				//支付成功
				$ret="success";
				$orderLog->log("googleafrica",array("order"=>$orderid,"money"=>$money,"serverresult"=>"success"));
			}
		}
		else
		{
			$ret="failure";
			$orderLog->log("googleafrica",array("order"=>$orderid,"money"=>$money,"serverresult"=>"signfaild"));
		}
		return $ret;
	}
	
	/*
	 *  谷歌V3商城校验,网上找到的验证代码，感谢原作者O(∩_∩)O~
	 */
	function chkGooglePlay($public_key, $purchaseData, $signature)
	{
		/*
		 $public_key=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn8Zo/abcdbRKBJl0VJLTk/O9Vca9mPiI4iEE+kiBrC7+zaZLuCaNN2v/38327TerDOAbp6BKXHl4p6J8Hf1kcja62W9lA+21/Qetrg1O6Q2pVNvWQnnlMzYHjFGChBclaMg20faVFPUFXfbRMEIsNbig5qu2Vg3fRQisQAmBIpKktnV5zOOw7gXfx3+EFql/87dhtk8gsnzvtYKu9iec98asctZ8FbpkNpyrh3czjXm/HnIUILPjLCRHX5Uk1zv7X7k0DbGbYFttdAQbi1byrZ2W5sbF93Cpy9NmldivnOFWLiqhiyck2Zsy3TDKMFnlrnI0gL1/AbCd67V7/d04NwIDAQAB
		 */
		$key =    "-----BEGIN PUBLIC KEY-----\n".
				chunk_split($public_key, 64,"\n").
				'-----END PUBLIC KEY-----';
		$key = openssl_get_publickey($key);
		$signature = base64_decode($signature);
		$ok = openssl_verify($purchaseData, $signature, $key, OPENSSL_ALGO_SHA1);//openssl_verify() 函数来验证sign签名是否正确，是通过指定的data数据和公钥相关的pub_key_id来实现的
		if($ok=='1') {
			return true;
		} else {
			return false;
		}
	}
}
